package com.sunfeng.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author sunfeng
 * @date 2021/04/09 14:38
 **/
@RestController
@Slf4j
public class FlowLimitController {
    @GetMapping("/testA")
    public String testA() {
        log.info(Thread.currentThread().getName() + "\t" + "...testA");
        return "------testA";
    }

    @GetMapping("/testB")
    public String testB() {
        log.info(Thread.currentThread().getName() + "\t" + "...testB");
        return "------testB";
    }

    /**
     *  RT 平均响应时间大于阈值 并且  时间窗口内的请求书大于5
     *
     *
     * @return
     */
    @GetMapping("/testD")
    public String testD() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("testD 测试RT");
        return "estD 测试RT";
    }

    @GetMapping("/testE")
    public String testE() {
        log.info("testE 测试异常数");
        int age = 10 / 0;
        return "------testE 测试异常数";
    }

    /**
     * 方法testHotKey里面第一个参数只要QPS超过每秒1次，马上降级处理 异常用了我们自己定义的兜底方法
     *
     * @param p1
     * @param p2
     * @return
     */
    //@SentinelResource 处理的是Sentinel控制台配置的违规情况，有blockHandler方法配置的兜底处理
    //RuntimeException，如 int a = 10/0 ; 这个是java运行时抛出的异常，RuntimeException，@RentinelResource不管
    //如果想要有配置出错，和运行出错的话，那么可以设置 fallback
    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey", blockHandler/*兜底方法*/ = "deal_testHotKey")
    public String testHotKey(@RequestParam(value = "p1", required = false) String p1,
                             @RequestParam(value = "p2", required = false) String p2) {
       //int age = 10/0;
        return "------testHotKey";
    }

    /*兜底方法*/
    public String deal_testHotKey(String p1, String p2, BlockException exception) {
        return "------deal_testHotKey,o(╥﹏╥)o";  //sentinel系统默认的提示：Blocked by Sentinel (flow limiting)
    }


}
